﻿using System;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Vincent
{
    /// <summary>
    /// 操作xml文件
    /// </summary>
    public class _Xml
    {
        /// <summary>
        /// 对象序列化成xml
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="SavePath">生成的xml保存到</param>
        /// <returns></returns>
        public static void SerializeObjToXml<T>(object sender, string SavePath)
        {
            try
            {
                XmlSerializer xmlSerial = new XmlSerializer(typeof(T));
                using (FileStream fs = new FileStream(SavePath, FileMode.Create))
                {
                    xmlSerial.Serialize(fs, sender);
                }
            }
            catch (XmlException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 对象序列化成XmlDocument对象
        /// </summary>
        /// <param name="sender">对象</param>
        /// <returns></returns>
        public static XmlDocument SerializeObjToXml<T>(object sender)
        {
            XmlDocument doc = null;
            try
            {
                doc = new XmlDocument();
                XmlSerializer xSerializer = new XmlSerializer(typeof(T));
                StringWriter sWriter = new StringWriter(CultureInfo.InvariantCulture);
                XmlTextWriter xTextWriter = new XmlTextWriter(sWriter);

                xSerializer.Serialize(xTextWriter, sender);
                doc.LoadXml(sWriter.ToString());


            }
            catch (Exception e)
            {
                throw e;
            }
            return doc;
        }

        /// <summary>
        /// xml 反序列化成对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="xmlFile">xml文件路径</param>
        /// <returns></returns>
        public static T SerializeXmlToObj<T>(string xmlFile)
        {
            try
            {
                XmlSerializer xmlSerial = new XmlSerializer(typeof(T));
                using (FileStream fs = File.OpenRead(xmlFile))
                {
                    return (T)xmlSerial.Deserialize(fs);
                }
            }
            catch (FileNotFoundException e)
            {
                throw e;
            }
        }
    }
}
